<template>
  <div class="my-report-container">
    <el-row :gutter="20">
      <!-- 左侧项目树 -->
      <el-col :span="6">
        <el-card class="project-tree-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Folder /></el-icon>
              <span>项目列表</span>
            </div>
          </template>
          
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索项目..."
              clearable
              size="small"
              class="custom-search-input"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <el-tree
            ref="projectTree"
            :data="projectTreeData"
            :props="treeProps"
            :filter-node-method="filterNode"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
            class="project-tree custom-project-tree"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <div class="node-content">
                  <el-icon class="node-icon"><Folder /></el-icon>
                  <span class="node-label">{{ node.label }}</span>
                </div>
                <div class="node-meta">
                  <el-tag v-if="data.state" :type="getStateTagType(data.state)" size="small" class="state-tag">
                    {{ data.state }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧功能页面 -->
      <el-col :span="18">
        <el-card class="function-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>{{ currentPageTitle }}</span>
              <el-tag v-if="currentProject" type="primary" size="small" style="margin-left: 10px;">
                {{ currentProject.project_name }}
              </el-tag>
            </div>
          </template>

          <!-- 功能页面导航 -->
          <div v-if="currentProject" class="function-nav">
            <el-button-group>
              <el-button 
                v-for="item in functionPages" 
                :key="item.key"
                :type="currentFunction === item.key ? 'primary' : 'default'"
                size="small"
                @click="switchFunction(item.key)"
              >
                <el-icon><component :is="item.icon" /></el-icon>
                {{ item.label }}
              </el-button>
            </el-button-group>
          </div>

          <!-- 页面内容区域 -->
          <div class="content-area">
            <!-- 项目信息页 -->
            <div v-if="currentFunction === 'info' && currentProject" class="info-page">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="项目编号">
                  <el-tag type="info">{{ currentProject.project_id }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="项目名称">
                  <span class="project-name">{{ currentProject.project_name }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="项目地点">
                  {{ currentProject.project_location }}
                </el-descriptions-item>
                <el-descriptions-item label="项目经理">
                  <el-tag type="success">{{ getUserNameById(currentProject.project_manager) }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="项目状态">
                  <el-tag :type="getStateTagType(currentProject.state)" size="small">
                    {{ currentProject.state }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="项目类型">
                  <el-tag type="info">{{ currentProject.project_type }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">
                  <div class="remark-content">
                    {{ currentProject.remark || '暂无备注信息' }}
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 功能页面内容 -->
            <div v-else-if="currentProject" class="function-page">
              <component 
                :is="getFunctionComponent(currentFunction)"
                :project-id="currentProject.id"
                :project-data="currentProject"
              />
            </div>

            <!-- 未选择项目时的提示 -->
            <div v-else class="placeholder-page">
              <el-empty description="请选择一个项目开始管理">
                <el-icon class="welcome-icon"><Folder /></el-icon>
              </el-empty>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Folder, Document, Search, User, DataBoard, Calendar, Refresh, 
  Flag, UserFilled, Warning, TrendCharts 
} from '@element-plus/icons-vue'
import { getProjectList } from '../../api/project'
import { getUserList } from '../../api/user'
import { getUserProjectList } from '../../api/userProject'

// 动态导入功能页面组件
import StakeholderManage from '../stakeholder/StakeholderManage.vue'
import ProjectStatus from '../project/ProjectStatus.vue'
import ProjectTimeline from '../project/ProjectTimeline.vue'
import ChangeRecord from '../project/ChangeRecord.vue'
import MilestonePlan from '../project/MilestonePlan.vue'
import ExperienceSummary from '../project/ExperienceSummary.vue'
import HumanResource from '../project/HumanResource.vue'
import IssueSummary from '../project/IssueSummary.vue'
import DocumentManage from '../project/DocumentManage.vue'
import WeightSetting from '../project/WeightSetting.vue'
import BiweeklyReport from '../project/BiweeklyReport.vue'
import ProjectEquipmentManagement from '../project/ProjectEquipmentManagement.vue'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const projectTreeData = ref([])
const userProjectList = ref([])
const currentProject = ref(null)
const currentFunction = ref('info')
const userList = ref([])
const projectTree = ref()

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const isAdmin = computed(() => currentUser.value.userType === '管理员')

// 树形配置
const treeProps = {
  children: 'children',
  label: 'project_name'
}

// 功能页面配置
const functionPages = [
  { key: 'info', label: '🧾 项目信息', icon: 'Document' },
  { key: 'stakeholder', label: '👥 干系人管理', icon: 'User' },
  { key: 'weight', label: '📈 权重设置', icon: 'TrendCharts' },
  { key: 'status', label: '🗓 项目状态', icon: 'DataBoard' },
  { key: 'timeline', label: '📅 实施周期', icon: 'Calendar' },
  { key: 'issue', label: '❗ 问题汇总', icon: 'Warning' },
  { key: 'human', label: '👨‍👩‍👧‍👦 人力资源', icon: 'UserFilled' },
  { key: 'change', label: '🔁 变更记录', icon: 'Refresh' },
  { key: 'milestone', label: '📌 节点计划', icon: 'Flag' },
  { key: 'experience', label: '📋 经验总结', icon: 'Document' },
  { key: 'document', label: '📂 资料管理', icon: 'Folder' },
  { key: 'biweekly-report', label: '📊 双周报表', icon: 'Document' },
  { key: 'equipment', label: '📦 设备管理', icon: 'Document' }
]

// 计算属性
const currentPageTitle = computed(() => {
  if (!currentProject.value) return '请选择项目'
  const page = functionPages.find(p => p.key === currentFunction.value)
  return page ? page.label : '项目功能'
})

// 获取当前页面标签
function getCurrentPageLabel() {
  const page = functionPages.find(p => p.key === currentFunction.value)
  return page ? page.label : '未知功能'
}

// 获取当前页面图标
function getCurrentPageIcon() {
  const page = functionPages.find(p => p.key === currentFunction.value)
  return page ? page.icon : 'Document'
}

// 获取功能组件
function getFunctionComponent(functionKey) {
  const componentMap = {
    'stakeholder': StakeholderManage,
    'status': ProjectStatus,
    'timeline': ProjectTimeline,
    'change': ChangeRecord,
    'milestone': MilestonePlan,
    'experience': ExperienceSummary,
    'human': HumanResource,
    'issue': IssueSummary,
    'document': DocumentManage,
    'weight': WeightSetting,
    'biweekly-report': BiweeklyReport,
    'equipment': ProjectEquipmentManagement
  }
  return componentMap[functionKey] || null
}

// 获取状态标签类型
function getStateTagType(state) {
  const stateMap = {
    '计划中': 'info',
    '进行中': 'primary',
    '已完成': 'success',
    '暂停': 'warning'
  }
  return stateMap[state] || 'info'
}

// 根据ID获取用户名
function getUserNameById(id) {
  const user = userList.value.find(u => u.id === id)
  return user ? user.Username : id
}

// 过滤节点
function filterNode(value, data) {
  if (!value) return true
  return data.project_name.toLowerCase().includes(value.toLowerCase())
}

// 处理节点点击
function handleNodeClick(data) {
  currentProject.value = data
  currentFunction.value = 'info' // 默认显示项目信息
}

// 切换功能页面
function switchFunction(functionKey) {
  currentFunction.value = functionKey
}

// 跳转到功能页面
function goToFunctionPage() {
  if (!currentProject.value) {
    ElMessage.warning('请先选择项目')
    return
  }
  
  const pageMap = {
    'stakeholder': 'stakeholder',
    'status': 'status',
    'timeline': 'timeline',
    'change': 'change',
    'milestone': 'milestone',
    'experience': 'experience',
    'human': 'human',
    'issue': 'issue',
    'document': 'document',
    'weight': 'weight'
  }
  
  const targetPage = pageMap[currentFunction.value]
  if (targetPage) {
    router.push(`/project/${targetPage}/${currentProject.value.id}`)
  }
}

// 加载项目列表
async function loadProjects() {
  try {
    const res = await getProjectList({ page: 1, pageSize: 1000 })
    let allProjects = res.records || []
    
    // 如果不是管理员，只显示分配给当前用户的项目
    if (!isAdmin.value) {
      const userProjectIds = userProjectList.value
        .filter(relation => relation.Userid === currentUser.value.id)
        .map(relation => relation.Porojectid)
      
      projectTreeData.value = allProjects.filter(project => 
        userProjectIds.includes(project.project_id)
      )
      
      console.log('当前用户ID:', currentUser.value.id)
      console.log('用户项目关联:', userProjectList.value)
      console.log('过滤后的项目ID:', userProjectIds)
      console.log('过滤后的项目:', projectTreeData.value)
    } else {
      projectTreeData.value = allProjects
    }
  } catch (error) {
    ElMessage.error('加载项目列表失败')
    console.error('加载项目列表失败:', error)
  }
}

// 加载用户列表
async function loadUsers() {
  try {
    const params = { page: 1, pageSize: 1000 }
    const res = await getUserList(params)
   // const res = await getUserList()
    userList.value = res.records || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 加载用户项目关联列表
async function loadUserProjects() {
  try {
    const params = { page: 1, pageSize: 1000 }
    const res = await getUserProjectList(params)
    //const res = await getUserProjectList()
    userProjectList.value = res.records || []
  } catch (error) {
    console.error('加载用户项目关联失败:', error)
  }
}

// 监听搜索关键词变化
watch(searchKeyword, (val) => {
  projectTree.value?.filter(val)
})

onMounted(() => {
  loadUserProjects().then(() => {
    loadProjects()
  })
  loadUsers()
})
</script>

<style scoped>
.my-report-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.project-tree-card,
.function-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.project-tree-card:hover,
.function-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #f0f0f0;
}

.search-box {
  margin: 20px;
  position: relative;
}

.custom-search-input {
  border-radius: 20px;
  transition: all 0.3s ease;
}

.custom-search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.custom-search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.custom-search-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  border-color: #409eff;
}

.search-icon {
  color: #909399;
  font-size: 16px;
}

.custom-project-tree {
  max-height: 100%;
  height: 1000px;
  overflow-y: auto;
  padding: 0 16px;
}

.custom-project-tree::-webkit-scrollbar {
  width: 6px;
}

.custom-project-tree::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 3px;
}

.custom-project-tree::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.custom-project-tree::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 8px 12px;
  border-radius: 8px;
  margin: 4px 0;
  transition: all 0.3s ease;
  background: transparent;
}

.tree-node:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  transform: translateX(4px);
}

.node-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
}

.node-icon {
  color: #67c23a;
  font-size: 18px;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.tree-node:hover .node-icon {
  color: #52c41a;
  transform: scale(1.1);
}

.node-label {
  flex: 1;
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.3s ease;
}

.tree-node:hover .node-label {
  color: #1890ff;
  font-weight: 600;
}

.node-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.state-tag {
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  padding: 2px 8px;
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.state-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.function-nav {
  margin-bottom: 20px;
  padding: 20px 0 16px 0;
  border-bottom: 1px solid #ebeef5;
}

.content-area {
  min-height: 400px;
}

.info-page {
  padding: 20px 0;
}

.project-name {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.remark-content {
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
}

.placeholder-page {
  padding: 60px 0;
  text-align: center;
}

:deep(.el-tree-node__content) {
  height: auto;
  border-radius: 8px;
  margin: 2px 0;
  padding: 0;
  transition: all 0.3s ease;
}

:deep(.el-tree-node__content:hover) {
  background-color: transparent;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
}

:deep(.el-tree-node.is-current > .el-tree-node__content .node-label) {
  color: #1890ff;
  font-weight: 600;
}

:deep(.el-tree-node.is-current > .el-tree-node__content .node-icon) {
  color: #1890ff;
}

:deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  background: #f5f7fa;
}

:deep(.el-button-group .el-button) {
  border-radius: 6px;
}

/* 大屏幕 (1200px 及以上) */
@media (min-width: 1200px) {
  .my-report-container {
    padding: 30px;
  }
  
  .custom-project-tree {
    height: 1200px;
  }
  
  .content-area {
    min-height: 500px;
  }
  
  .search-box {
    margin: 24px;
  }
  
  .tree-node {
    padding: 10px 16px;
    margin: 6px 0;
  }
  
  .node-icon {
    font-size: 20px;
  }
  
  .node-label {
    font-size: 15px;
  }
}

/* 中等屏幕 (768px - 1199px) */
@media (min-width: 768px) and (max-width: 1199px) {
  .my-report-container {
    padding: 20px;
  }
  
  .custom-project-tree {
    height: 800px;
  }
  
  .content-area {
    min-height: 400px;
  }
  
  .search-box {
    margin: 18px;
  }
  
  .tree-node {
    padding: 8px 12px;
    margin: 4px 0;
  }
  
  .node-icon {
    font-size: 18px;
  }
  
  .node-label {
    font-size: 14px;
  }
}

/* 小屏幕 (480px - 767px) */
@media (min-width: 480px) and (max-width: 767px) {
  .my-report-container {
    padding: 15px;
  }
  
  .custom-project-tree {
    height: 600px;
  }
  
  .content-area {
    min-height: 350px;
  }
  
  .search-box {
    margin: 16px;
  }
  
  .function-nav {
    overflow-x: auto;
  }
  
  .el-button-group {
    display: flex;
    flex-wrap: nowrap;
  }
  
  .card-header {
    font-size: 14px;
    padding: 14px 16px;
  }
  
  .project-name {
    font-size: 14px;
  }
  
  .tree-node {
    padding: 6px 10px;
    margin: 3px 0;
  }
  
  .node-icon {
    font-size: 16px;
  }
  
  .node-label {
    font-size: 13px;
  }
  
  .state-tag {
    font-size: 10px;
    padding: 1px 6px;
  }
}

/* 超小屏幕 (480px 以下) */
@media (max-width: 479px) {
  .my-report-container {
    padding: 10px;
  }
  
  .custom-project-tree {
    height: 500px;
  }
  
  .content-area {
    min-height: 300px;
  }
  
  .search-box {
    margin: 12px;
  }
  
  .function-nav {
    overflow-x: auto;
    margin-bottom: 15px;
  }
  
  .el-button-group {
    display: flex;
    flex-wrap: nowrap;
  }
  
  .el-button-group .el-button {
    font-size: 12px;
    padding: 8px 12px;
  }
  
  .card-header {
    font-size: 13px;
    gap: 6px;
    padding: 12px 14px;
  }
  
  .project-name {
    font-size: 13px;
  }
  
  .info-page {
    padding: 15px 0;
  }
  
  .placeholder-page {
    padding: 40px 0;
  }
  
  .tree-node {
    padding: 5px 8px;
    margin: 2px 0;
    gap: 6px;
  }
  
  .node-icon {
    font-size: 14px;
  }
  
  .node-label {
    font-size: 12px;
  }
  
  .state-tag {
    font-size: 9px;
    padding: 1px 4px;
  }
}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 600px) {
  .my-report-container {
    padding: 10px;
  }
  
  .custom-project-tree {
    height: 400px;
  }
  
  .content-area {
    min-height: 250px;
  }
  
  .info-page {
    padding: 10px 0;
  }
  
  .placeholder-page {
    padding: 20px 0;
  }
  
  .search-box {
    margin: 10px;
  }
  
  .tree-node {
    padding: 4px 8px;
    margin: 1px 0;
  }
}

/* 高分辨率屏幕优化 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .project-tree-card,
  .function-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }
  
  .card-header {
    font-weight: 700;
  }
  
  .project-name {
    font-weight: 700;
  }
  
  .custom-search-input :deep(.el-input__wrapper) {
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }
}

/* 打印样式 */
@media print {
  .my-report-container {
    padding: 0;
    background: white;
  }
  
  .project-tree-card,
  .function-card {
    box-shadow: none;
    border: 1px solid #ddd;
  }
  
  .function-nav {
    display: none;
  }
  
  .search-box {
    display: none;
  }
  
  .tree-node:hover {
    background: transparent;
    transform: none;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .project-tree-card,
  .function-card {
    background: #1f1f1f;
    border-color: #434343;
  }
  
  .card-header {
    background: linear-gradient(135deg, #262626 0%, #1f1f1f 100%);
    border-bottom-color: #434343;
    color: #ffffff;
  }
  
  .tree-node:hover {
    background: linear-gradient(135deg, #1f1f1f 0%, #262626 100%);
  }
  
  .node-label {
    color: #ffffff;
  }
  
  .custom-search-input :deep(.el-input__wrapper) {
    background: #262626;
    border-color: #434343;
  }
}
</style> 